import Axios from 'axios';
import special from '../mode/SpecialSubject';
import Proudct from '../mode/Product';
import {IsNullObject} from '../utils/utils';

import {taobaoParam} from '../utils/TbParams';

const appKey = 'baoganxing';
const sourceUrl = 'http://v2.api.haodanku.com';

function CreateProducts(data) {
  const lists = [];
  data.map((item, key) => {
    lists.push(CreateProduct(item));
  });
  return lists;
}

function CreateProduct(item) {
  let temp = new Proudct();
  temp.productId = item.itemid;

  temp.picUrl =
    item.itempic.indexOf('http') === 0
      ? item.itempic
      : 'https://' + item.itempic;
  temp.couponMoney = item.couponmoney;
  temp.title = item.itemshorttitle;
  temp.longTitle = item.itemtitle;
  if (temp.longTitle === '' || temp.longTitle === undefined) {
    temp.longTitle = temp.title;
  }

  temp.quanhouPrice = item.itemendprice;
  temp.realPrice = item.itemprice;
  // temp.smallImages = item.smallImages
  temp.user_type = item.shoptype === 'C' ? 1 : 0;
  temp.volume = item.itemsale;
  temp.couponUrl = item.couponurl;
  temp.coupon_start_time = item.couponstarttime;
  temp.dy_video_url = item.dy_video_url;
  temp.dy_video_title = item.dy_video_title;

  temp.shopname = item.shopname;

  if (temp.coupon_start_time === undefined) {
    temp.coupon_start_time = '';
  }

  temp.coupon_end_time = item.couponendtime;
  if (temp.coupon_end_time === undefined) {
    temp.coupon_end_time = '';
  }
  temp.recommendation = item.itemdesc;
  temp.todaysale = item.todaysale;
  return temp;
}

/*
 * 获取专题数据
 * */
export function specialSubject() {
  return new Promise((resolve) => {
    let url = '{0}/get_subject/apikey/{1}';
    url = url.format(sourceUrl, appKey);
    Axios.get(url)
      .then((res) => {
        if (res.data.code === 1) {
          const lists = [];
          var imageSouce = 'http://img-haodanku-com.cdn.fudaiapp.com/{0}';
          res.data.data.map((item) => {
            var temp = new special();
            temp.id = item.id;
            temp.name = item.name;
            temp.image = imageSouce.format(item.app_image);
            temp.content = item.content;
            lists.push(temp);
          });
          resolve(lists);
        } else {
          resolve([]);
        }
      })
      .catch((e) => {});
  });
}

/**
 * 获取专题数据
 * @param {*} id
 */
export function get_subject_item(id) {
  return new Promise((resolve) => {
    var url = '{0}/get_subject_item/apikey/{1}/id/{2}';
    url = url.format(sourceUrl, appKey, id);
    Axios.get(url).then((res) => {
      res = res.data;

      // eslint-disable-next-line radix
      if (res.code !== 1) {
        resolve([]);
      } else {
        let ttt = CreateProducts(res.data);
        resolve(ttt);
      }
    });
  }).catch((e) => {});
}

/*
 * 高佣专场商品
 * */
export function highItems(min_id, cat_id) {
  return new Promise((resolve) => {
    let url = '{0}/get_highitems/apikey/{1}/back/20/min_id/{2}/cat_id/{3}';
    url = url.format(sourceUrl, appKey, min_id, cat_id);
    Axios.get(url).then((res) => {
      res = res.data;
      if (parseInt(res.code) !== 200) {
        resolve({min_id: min_id, list: []});
      } else {
        if (res.data.length <= 0) {
          resolve({min_id: min_id, list: []});
        } else {
          resolve({min_id: res.min_id, list: CreateProducts(res.data)});
        }
      }
    });
  }).catch(() => {
    console.log('获取高佣专场商品~~~');
  });
}

/*
 *获取热搜
 * */
export function hot_key() {
  return new Promise((resolve) => {
    let url = '{0}/hot_key/apikey/{1}';
    url = url.format(sourceUrl, appKey);
    Axios.post(url).then((res) => {
      resolve(res.data.data);
    });
  }).catch((e) => {});
}

/*
 * 超级搜索
 * */
export function superSearch(keyword, min_id, sort) {
  return new Promise((resolve) => {
    let url =
      '{0}/supersearch/apikey/{1}/keyword/{2}/back/50/min_id/{3}/tb_p/1/sort/{4}/is_tmall/0/is_coupon/1/limitrate/0';
    url = url.format(sourceUrl, appKey, keyword, min_id, sort);
    Axios.post(url).then((res) => {
      if (res.data.code === 1) {
        resolve({min_id: res.data.min_id, list: CreateProducts(res.data.data)});
      } else {
        resolve(null);
      }
    });
  }).catch((e) => {});
}

/**
 * 好单网全网搜索
 * @param {*} cid
 * @param {*} sort
 * @param {*} page
 * @param {*} filtrate_type 聚划算
 */
export function get_allitem_list(cid, sort, page, filtrate_type) {
  return new Promise((resolve) => {
    filtrate_type = IsNullObject(filtrate_type) ? '' : filtrate_type;
    var url = `https://www.haodanku.com/allitem/get_allitem_list?keyword=&shopsearch=&brand_name=&cid=${cid}&min_price=&max_price=&filtrate_type=${filtrate_type}&min_sale=&min_rate=&min_tkMoney=&min_avg=&min_coupon=&p=${page}&shoptype=&discount=&favorites_count=&min_itemprice=&max_itemprice=&sort=${sort}`;
    Axios.get(url).then((res) => {
      res = res.data;
      // eslint-disable-next-line radix
      if (parseInt(res.code) !== 200) {
        resolve({data: [], min_id: page});
      } else {
        if (res.item_info.length <= 0) {
          resolve({data: [], min_id: page});
        } else {
          let ttt = CreateProducts(res.item_info);
          resolve({data: ttt, min_id: page + 1});
        }
      }
    });
  }).catch((e) => {});
}

/*
 * 低价包邮* 2. 9.9专区；3. 6.9专区；4. 3.9专区（默认1）
 * */
export function getLowPrice(type, min_id, order) {
  return new Promise((resolve) => {
    var url = `${sourceUrl}/low_price_Pinkage_data/apikey/${appKey}/type/${type}/min_id/${min_id}/back/20/order/${order}`;
    Axios.get(url).then((res) => {
      res = res.data;
      if (parseInt(res.code) !== 1) {
        resolve(null);
      } else {
        if (res.data.length <= 0) {
          resolve(null);
        } else {
          let ttt = CreateProducts(res.data);

          resolve({data: ttt, min_id: res.min_id});
        }
      }
    });
  }).catch(() => {});
}

/*
 *偏远地区包邮商品
 * */
export function get_free_shipping(cat_id, min_id) {
  return new Promise((resolve) => {
    var url = `${sourceUrl}/get_free_shipping_data/apikey/${appKey}/min_id/${min_id}/cat_id/${cat_id}/back/20`;
    Axios.get(url).then((res) => {
      res = res.data;
      if (parseInt(res.code) !== 1) {
        resolve(null);
      } else {
        if (res.data.length <= 0) {
          resolve(null);
        } else {
          let ttt = CreateProducts(res.data);
          resolve({data: ttt, min_id: res.min_id});
        }
      }
    });
  }).catch(() => {});
}

/*
 * 快抢商品
 * */
export function getFastBuy(list_type, list_page) {
  return new Promise((resolve) => {
    var url = `${sourceUrl}/fastbuy/apikey/${appKey}/hour_type/${list_type}/min_id/${list_page}`;
    Axios.get(url).then((res) => {
      res = res.data;
      if (parseInt(res.code) !== 1) {
        resolve(null);
      } else {
        if (res.data.length <= 0) {
          resolve(null);
        } else {
          let ttt = CreateProducts(res.data);
          resolve({data: ttt, min_id: res.min_id});
        }
      }
    });
  }).catch(() => {});
}

/*
 *达人说API
 * */
export function talent_info(sort) {
  return new Promise((resolve) => {
    Axios.get(
      `${sourceUrl}/talent_info/apikey/${appKey}/talentcat/${sort}`,
    ).then((res) => {
      resolve(res.data);
    });
  }).catch(() => {});
}

/*
 * 各大榜单API
 * */
export function sales_list(sale_type, page) {
  return new Promise((resolve) => {
    Axios.get(
      `${sourceUrl}/sales_list/apikey/${appKey}/sale_type/${sale_type}/min_id/${page}/back/20`,
    ).then((res) => {
      res = res.data;
      if (parseInt(res.code) !== 1) {
        resolve({data: [], min_id: 1});
      } else {
        let ttt = CreateProducts(res.data);
        resolve({data: ttt, min_id: res.min_id});
      }
    });
  }).catch(() => {});
}

/*
 * 差异化货品 1精选好货，2大额神券，39.9元封顶，4时尚女装，5潮流男装，6精致潮鞋
 * */
export function tb_items_material_dat(cat_id, min_id) {
  return new Promise((resolve) => {
    Axios.get(
      `${sourceUrl}/tb_items_material_data/apikey/${appKey}/cat_id/${cat_id}/min_id/${min_id}/back/20`,
    ).then((res) => {
      res = res.data;
      if (parseInt(res.code) !== 200) {
        resolve({data: [], min_id: 1});
      } else {
        let ttt = CreateProducts(res.data);
        resolve({data: ttt, min_id: res.min_id});
      }
    });
  }).catch(() => {});
}

/*
 * 超级分类
 * */
export function super_classify() {
  return new Promise((resolve) => {
    Axios.get(`${sourceUrl}/super_classify/apikey/${appKey}`)
      .then((res) => {
        res = res.data;
        if (parseInt(res.code) !== 1) {
          resolve(null);
        } else {
          resolve(res.general_classify);
        }
      })
      .catch((e) => {
        console.log('报错：' + e);
      });
  });
}

/*
 * 抖货数据
 * */
export function trill_data(min_id, cat_id) {
  return new Promise((resolve) => {
    Axios.get(
      `${sourceUrl}/get_trill_data/apikey/${appKey}/min_id/${min_id}/back/20/cat_id/${cat_id}`,
    ).then((res) => {
      // console.log(res)
      res = res.data;
      if (parseInt(res.code) !== 1) {
        resolve(null);
      } else {
        let ttt = CreateProducts(res.data);
        resolve({data: ttt, min_id: res.min_id});
      }
    });
  });
}
//转高佣金
export function Tao_haoDao_Ratesurl(itemid, title) {
  return new Promise((resolve, reject) => {
    let formData = new FormData();
    formData.append('apikey', appKey);
    formData.append('itemid', itemid);
    formData.append('pid', taobaoParam().Pid);
    formData.append('tb_name', taobaoParam().tb_name);
    formData.append('get_taoword', 1);
    formData.append('title', title);

    Axios({
      method: 'post',
      url: 'http://v2.api.haodanku.com/ratesurl',
      data: formData,
      headers: {'content-type': 'application/x-www-form-urlencoded'},
    }).then((res) => {
      // console.log(res.data)
      if (res.data == null) {
        resolve(null);
      } else {
        if (parseInt(res.data.code) !== 1) {
          resolve(null);
        } else {
          resolve({
            coupon_click_url: res.data.data.coupon_click_url,
            item_url: res.data.data.item_url,
            taoword: res.data.data.taoword,
          });
        }
      }
    });
  }).catch((e) => {
    console.log(e);
  });
}
